﻿using Sidvall.Serialization;
using System;
using System.Globalization;

namespace Sidvall.UI.Wpf.Converters
{
    public class EnumToBooleanConverter : ValueToBooleanConverterBase
    {
        #region Public Members

        #region BooleanToValue

        protected override object BooleanToValue(object value, Type targetType, object parameter, CultureInfo culture)
        {
            if (value.ToBoolean(false))
            {
                if (!this.Not)
                    return GetValue(targetType, parameter);
                else
                    return null;
            }
            else
            {
                if (!this.Not)
                    return null;
                else
                    return GetValue(targetType, parameter);
            }
        }

        #endregion

        #endregion
        #region Private Members

        #region GetValue

        private object GetValue(Type targetType, object parameter)
        {
            if (!IsNullableType(targetType))
            {
                return Enum.Parse(targetType, parameter.ToString(string.Empty));
            }
            else
            {
                var parameterValue = parameter.ToString(string.Empty);
                if (!string.IsNullOrWhiteSpace(parameterValue))
                {
                    targetType = targetType.GenericTypeArguments[0];
                    return Enum.Parse(targetType, parameter.ToString(string.Empty));
                }
                return null;
            }
        }

        #endregion
        #region IsNullableType

        private bool IsNullableType(Type type)
        {
            return type.IsGenericType && type.GetGenericTypeDefinition() == typeof(Nullable<>);
        }

        #endregion

        #endregion
    }
}
